﻿#include "serialportwidget.h"

#include <QLabel>
#include <QLineEdit>
#include <QComboBox>
#include <QPushButton>
#include <QGridLayout>
#include <QString>
#include <QTimer>
#include <QList>
#include <unistd.h>
#include <QTextEdit>
#include <QListView>

#include "serialport.h"
#include "serialportreadthread.h"
#include "configargs.h"

SerialPortWidget::SerialPortWidget(QWidget *parent) : QWidget(parent)
{
    im = new InputMethod;
	sentcont=0;
	receivecont=0;
	autouartflag=0;
	
    QLabel			*pNameLabel1			= new QLabel;
    QLabel			*pBaudrateLabel			= new QLabel;
    QLabel			*pDataBitsLabel			= new QLabel;
    QLabel			*pParityLable			= new QLabel;
    QLabel			*pStopBitsLabel			= new QLabel;
    QLabel			*pMsLabel			    = new QLabel;
    QLabel			*pSentCountLabel			    = new QLabel;
    QLabel			*pRecevCountLabel			    = new QLabel;



    pOpenButton			= new QPushButton;
    pSentButton         = new QPushButton;
    pCloseButton		= new QPushButton;
    pCleanButton		= new QPushButton;

	m_pAutoRadioBut   = new QCheckBox;
	m_pHexOrChar      = new QCheckBox;
	
    m_pAutoRadioBut->setStyleSheet("QCheckBox::indicator {width: 15px; height: 15px;}QCheckBox::indicator:checked {image: url(:/image/linuxdesktop/settingsicon/checkbox.png);}");
	m_pHexOrChar->setStyleSheet("QCheckBox::indicator {width: 15px; height: 15px;}QCheckBox::indicator:checked {image: url(:/image/linuxdesktop/settingsicon/checkbox.png);}");

	m_pAutoTimer      =new QTimer;
    m_pReceiveEdit			= new QPlainTextEdit;
    m_pSendEdit				= new QLineEdit;
    m_pTimeEdit             = new QLineEdit;
    m_pSentCountEdit        = new QLineEdit;
    m_pReciveCountEdit      = new QLineEdit;
    m_pReceiveTimer			= new QTimer;
    m_pBandrateCombo		= new QComboBox;
    m_pDataBitsCombo		= new QComboBox;
    m_pParityCombo			= new QComboBox;
    m_pStopBitsCombo		= new QComboBox;
    m_pNameCombo            = new QComboBox;

    m_pSendEdit->installEventFilter(im);
    m_pSendEdit->setObjectName("m_pSendEdit");
//    connect(im,SIGNAL(setImObjName(QString)),this,SLOT(createImConnect(QString)));//connect the input method

    m_pTimeEdit->installEventFilter(im);
    m_pTimeEdit->setObjectName("m_pTimeEdit");
    connect(im,SIGNAL(setImObjName(QString)),this,SLOT(createImConnect(QString)));//connect the input method


    pNameLabel1			->setText(tr("串  口："));
    pBaudrateLabel		->setText(tr("波特率："));
    pDataBitsLabel		->setText(tr("数据位："));
    pParityLable		->setText(tr("校验位："));
    pStopBitsLabel		->setText(tr("停止位："));
    pMsLabel            ->setText("ms");
 


    
	m_pHexOrChar		->setText(tr("HEX"));


    QList<QString>	bandrateList;
    bandrateList	<< "4800"
                    << "9600"
                    << "19200"
                    << "38400"
                    << "57600"
                    << "115200" ;

    QList<QString>	dataBitsList;
    dataBitsList	<< "5"
                    << "6"
                    << "7"
                    << "8";

    QList<QString>	parityList;
    parityList		<< "N"
                    << "E"
                    << "O"
                    << "S";

    QList<QString>	stopBitsList;
    stopBitsList	<< "1"
                    << "1.5"
                    << "2";

	QList<QString>	nameList;

	if(g_lcdsize == LCDSIZE_480x272)
	{
		nameList		<< "COM1"
						<< "COM2"
						<< "485_0";

	}else{
		
		nameList		<< "COM1"
						<< "COM2"
						<< "COM3"
                        << "COM4"
                        << "COM5";

	}

	if(g_lcdsize == LCDSIZE_800x600){
		if(g_cmdline.contains("can=disable"))
		{
			nameList << "COM5";
		}
	}
    

    m_pBandrateCombo->addItems(bandrateList);
    m_pBandrateCombo->setView(new QListView());
    m_pDataBitsCombo->addItems(dataBitsList);
    m_pDataBitsCombo->setView(new QListView());
    m_pParityCombo->addItems(parityList);
    m_pParityCombo->setView(new QListView());
    m_pStopBitsCombo->addItems(stopBitsList);
    m_pStopBitsCombo->setView(new QListView());
    m_pNameCombo->addItems(nameList);
    m_pNameCombo->setView(new QListView());


    pNameLabel1			->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pBaudrateLabel		->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pDataBitsLabel		->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pParityLable		->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pStopBitsLabel		->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_pBandrateCombo	->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_pDataBitsCombo	->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_pNameCombo        ->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_pParityCombo		->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_pStopBitsCombo	->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pOpenButton			->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pSentButton			->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pCloseButton		->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pCleanButton		->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_pReceiveEdit		->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_pSendEdit			->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
   // m_pTimeEdit         ->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_pAutoRadioBut     ->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_pReceiveEdit->document()->setMaximumBlockCount(1000);

    connect(pOpenButton,		SIGNAL(clicked()), this, SLOT(openSerialPort()));
    connect(pSentButton,		SIGNAL(clicked()), this, SLOT(sendData()));
    connect(pCloseButton,		SIGNAL(clicked()), this, SLOT(closeSerialPort()));
    connect(pCleanButton,		SIGNAL(clicked()), this, SLOT(cleanReceiveLabel()));
    connect(m_pAutoRadioBut,    SIGNAL(clicked()),     this,   SLOT(Autohave()));
	connect(m_pHexOrChar,    	SIGNAL(clicked()),     this,   SLOT(HexOrChar()));

	m_pReceiveEdit->setCenterOnScroll(false);   //cursor is always at below
	m_pReceiveEdit->setMaximumBlockCount(500);    //最大行数

    QGridLayout		*pMainLayout		= new QGridLayout;
    pMainLayout->addWidget(pNameLabel1,			0, 0, 1, 1);
    pMainLayout->addWidget(m_pNameCombo,		0, 1, 1, 2);
    pMainLayout->addWidget(pBaudrateLabel,		1, 0, 1, 1);
    pMainLayout->addWidget(m_pBandrateCombo,	1, 1, 1, 2);
    pMainLayout->addWidget(pDataBitsLabel,		2, 0, 1, 1);
    pMainLayout->addWidget(m_pDataBitsCombo,	2, 1, 1, 2);
    pMainLayout->addWidget(pParityLable,		3, 0, 1, 1);
    pMainLayout->addWidget(m_pParityCombo,		3, 1, 1, 2);
    pMainLayout->addWidget(pStopBitsLabel,		4, 0, 1, 1);
    pMainLayout->addWidget(m_pStopBitsCombo,	4, 1, 1, 2);

    QHBoxLayout * subHLayout1 = new QHBoxLayout;
    QHBoxLayout * subHLayout2 = new QHBoxLayout;

    QVBoxLayout * subVLayout = new QVBoxLayout;

	m_pTimeEdit 		->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
	m_pSentCountEdit	->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
	m_pReciveCountEdit	->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

	if(g_lcdsize == LCDSIZE_480x272)
	{
		pOpenButton			->setText(tr("打开"));
		pSentButton			->setText(tr("发送"));
		pCloseButton		->setText(tr("关闭"));
		pCleanButton		->setText(tr("清空"));
		m_pAutoRadioBut     ->setText(tr("自发(ms):"));
		pSentCountLabel     ->setText(tr("发"));
		pRecevCountLabel    ->setText(tr("接"));
		subHLayout1->addWidget(m_pAutoRadioBut);
		subHLayout1->addWidget(m_pTimeEdit);
		subHLayout1->addWidget(m_pHexOrChar);
		m_pTimeEdit->setMaximumSize(70, 70);

		//	subHLayout2->addWidget(m_pHexOrChar);
		subHLayout2->addWidget(pSentCountLabel);
		subHLayout2->addWidget(m_pSentCountEdit);
		m_pSentCountEdit->setMaximumSize(100, 50);
		m_pSentCountEdit->setEnabled(false);

		subHLayout2->addWidget(pRecevCountLabel);
		subHLayout2->addWidget(m_pReciveCountEdit);
		m_pReciveCountEdit->setMaximumSize(100, 50);
		m_pReciveCountEdit->setEnabled(false);

		subVLayout->addLayout(subHLayout1);
		subVLayout->addLayout(subHLayout2);

		pMainLayout->addLayout(subVLayout,		    5, 0, 2, 3);
		pMainLayout->addWidget(m_pReceiveEdit,		0, 3, 4, 8);
		pMainLayout->addWidget(m_pSendEdit,			4, 3, 1, 8);
		pMainLayout->addWidget(pOpenButton,			5, 3, 2, 2);
		pMainLayout->addWidget(pCloseButton,		5, 5, 2, 2);
		pMainLayout->addWidget(pCleanButton,		5, 7, 2, 2);
		pMainLayout->addWidget(pSentButton,			5, 9, 2, 2);

	}else{	
		pOpenButton			->setText(tr("打  开"));
		pSentButton			->setText(tr("发  送"));
		pCloseButton		->setText(tr("关  闭"));
		pCleanButton		->setText(tr("清  空"));
		m_pAutoRadioBut     ->setText(tr("自动发送周期 (ms) : "));
		pSentCountLabel     ->setText(tr("发送"));
		pRecevCountLabel    ->setText(tr("接收"));
		subHLayout1->addWidget(m_pAutoRadioBut);
	    subHLayout1->addWidget(m_pTimeEdit);
	    m_pTimeEdit->setMaximumSize(125, 70);

		subHLayout2->addWidget(m_pHexOrChar);
	    subHLayout2->addWidget(pSentCountLabel);
	    subHLayout2->addWidget(m_pSentCountEdit);
	    m_pSentCountEdit->setMaximumSize(120, 50);
	    m_pSentCountEdit->setEnabled(false);
	 
	    subHLayout2->addWidget(pRecevCountLabel);
	    subHLayout2->addWidget(m_pReciveCountEdit);
	    m_pReciveCountEdit->setMaximumSize(120, 50);
		m_pReciveCountEdit->setEnabled(false);
		
	    subVLayout->addLayout(subHLayout1);
	    subVLayout->addLayout(subHLayout2);

	    pMainLayout->addLayout(subVLayout,		    5, 0, 2, 3);
	    pMainLayout->addWidget(m_pReceiveEdit,		0, 3, 4, 8);
	    pMainLayout->addWidget(m_pSendEdit,			4, 3, 1, 8);
	    pMainLayout->addWidget(pOpenButton,			5, 3, 2, 1);
	    pMainLayout->addWidget(pCloseButton,		5, 4, 2, 1);
	    pMainLayout->addWidget(pCleanButton,		5, 8, 2, 1);
	    pMainLayout->addWidget(pSentButton,			5, 9, 2, 1);
	}
	
    this->setLayout(pMainLayout);

    m_pMySerialPort = new SerialPort();
    m_pReadThread = new SerialPortReadThread();

    connect(m_pReadThread, SIGNAL(receiveSignal(QString)), this, SLOT(receiveData(QString)));
    connect(m_pAutoTimer,      SIGNAL(timeout()),     this,   SLOT(timeAuto()));

    m_pBandrateCombo->setCurrentIndex(5);
    m_pDataBitsCombo->setCurrentIndex(3);
    m_pNameCombo->setCurrentIndex(1);
    m_pSendEdit->setText(tr("1234567890abcdefg"));
    m_pTimeEdit->setText(tr("10"));
    m_pSentCountEdit->setText(tr("0"));
    m_pReciveCountEdit->setText(tr("0"));

	pCloseButton->setEnabled(false);
	pSentButton->setEnabled(false);
	m_pAutoRadioBut->setEnabled(false);
//	m_pTimeEdit->setEnabled(false);
	
	pCloseButton->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");
	pSentButton->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");

}

SerialPortWidget::~SerialPortWidget(){
    closeSerialPort();
  //  delete m_pReadThread;
}

void SerialPortWidget::Autohave()
{

    if(m_pAutoRadioBut->isChecked()) {
        if( (!IsNub(m_pTimeEdit->text())) ) // bu shi shu zi
             m_pTimeEdit->setText(tr("300"));
        tmiems=m_pTimeEdit->text().toInt();
        m_pAutoTimer->start(tmiems);
        pSentButton->setEnabled(false);
    }else{
        m_pAutoTimer->stop();
        pSentButton->setEnabled(true);
    }
}

void SerialPortWidget::HexOrChar()
{
	qDebug() << "in function HexOrChar";

	if(m_pReadThread->HexOrChar_flag == 0)
	{
		m_pReadThread->HexOrChar_flag = 1;
//		qDebug() << "is char now";
	}
	else
	{
//		qDebug() << "is hex now";
		m_pReadThread->HexOrChar_flag = 0;
	}
	
}




void SerialPortWidget::timeAuto()
{
   // if(haveopen)
   if(1==autouartflag)
    sendData();
    m_pSentCountEdit->setText(QString::number(sentcont));
}

void SerialPortWidget::createImConnect(QString ObjName)
{
    disconnect(im->keyboard,SIGNAL(setvalue(QString)),m_pSendEdit,SLOT(setText(QString)));
     disconnect(im->keyboard,SIGNAL(setvalue(QString)),m_pTimeEdit,SLOT(setText(QString)));
    if(ObjName=="m_pSendEdit")
        connect(im->keyboard,SIGNAL(setvalue(QString)),m_pSendEdit,SLOT(setText(QString)));

    if(ObjName=="m_pTimeEdit")
        connect(im->keyboard,SIGNAL(setvalue(QString)),m_pTimeEdit,SLOT(setText(QString)));


}

void SerialPortWidget::sendData()
{
    if(1==autouartflag){
//    QByteArray temp = m_pSendEdit->text().toUtf8();
	QByteArray temp = m_pSendEdit->text().toLocal8Bit();
    char *pBuff = temp.data();

    m_pMySerialPort->write(pBuff, temp.length());

    if(sentcont < 18446744073709551610)
   		sentcont+=m_pSendEdit->text().length();
    else
        sentcont=0;
	
    m_pSentCountEdit->setText(QString::number(sentcont));

    }
}

void SerialPortWidget::openSerialPort()
{
    QByteArray name = m_pNameCombo->currentText().toUtf8();
    char *pName = const_cast<char*>(name.data());

    pOpenButton->setEnabled(false);
    pCloseButton->setEnabled(true);
	pSentButton->setEnabled(true);
	m_pBandrateCombo	->setEnabled(false);
    m_pDataBitsCombo	->setEnabled(false);
    m_pNameCombo        ->setEnabled(false);
    m_pParityCombo		->setEnabled(false);
    m_pStopBitsCombo	->setEnabled(false);
    m_pAutoRadioBut		->setEnabled(true);
//	m_pTimeEdit			->setEnabled(false);

    
	m_pBandrateCombo	->setStyleSheet("QComboBox {border: 2px solid #b4d3e9; background-color: #b4d3e9;   border-radius: 0px;    color: #ffffff;} QComboBox::drop-down {background-color: #b4d3e9;}");
	m_pDataBitsCombo	->setStyleSheet("QComboBox {border: 2px solid #b4d3e9; background-color: #b4d3e9;   border-radius: 0px;    color: #ffffff;} QComboBox::drop-down {background-color: #b4d3e9;}");
	m_pNameCombo		->setStyleSheet("QComboBox {border: 2px solid #b4d3e9; background-color: #b4d3e9;   border-radius: 0px;    color: #ffffff;} QComboBox::drop-down {background-color: #b4d3e9;}");
	m_pParityCombo		->setStyleSheet("QComboBox {border: 2px solid #b4d3e9; background-color: #b4d3e9;   border-radius: 0px;    color: #ffffff;} QComboBox::drop-down {background-color: #b4d3e9;}");
	m_pStopBitsCombo	->setStyleSheet("QComboBox {border: 2px solid #b4d3e9; background-color: #b4d3e9;   border-radius: 0px;    color: #ffffff;} QComboBox::drop-down {background-color: #b4d3e9;}");

	pOpenButton->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");
	pCloseButton->setStyleSheet("QPushButton{background-color: #4a95c9; color: #ffffff; border: 1px solid #4a95c9;}");
	pSentButton->setStyleSheet("QPushButton{background-color: #4a95c9; color: #ffffff; border: 1px solid #4a95c9;}");

    QByteArray parity = m_pParityCombo->currentText().toUtf8();
    char *pParity = parity.data();
	autouartflag=1;
//    char *pParity;
//    Transform::qstringToChar2(m_pParityCombo->currentText(), pParity);

    m_pMySerialPort->open(pName,
                         m_pBandrateCombo->currentText().toInt(),
                         m_pDataBitsCombo->currentText().toInt(),
                         pParity,
                         m_pStopBitsCombo->currentText().toInt());

    m_pReadThread->setWeiQianFunctions(m_pMySerialPort);

#if 0
    if(m_pReadThread->isRunning()) {
    	qDebug("it's running");
        m_pReadThread->stop();
        usleep(100000);
    }
#endif    
    m_pReadThread->start();
}

void SerialPortWidget::closeSerialPort()
{
    autouartflag=0;

    m_pAutoTimer->stop();
    m_pAutoRadioBut->setCheckState(Qt::Unchecked);

    pOpenButton->setEnabled(true);
    pCloseButton->setEnabled(false);
//	pCleanButton->setEnabled(false);
	pSentButton->setEnabled(false);
	m_pBandrateCombo	->setEnabled(true);
    m_pDataBitsCombo	->setEnabled(true);
    m_pNameCombo        ->setEnabled(true);
    m_pParityCombo		->setEnabled(true);
    m_pStopBitsCombo	->setEnabled(true);
	m_pAutoRadioBut		->setEnabled(false);
//    m_pTimeEdit			->setEnabled(true);

    
	m_pBandrateCombo	->setStyleSheet("QComboBox {border: 2px solid #4a95c9; background-color: #4a95c9;    border-radius: 0px;    color: #ffffff;}");
	m_pDataBitsCombo	->setStyleSheet("QComboBox {border: 2px solid #4a95c9; background-color: #4a95c9;    border-radius: 0px;    color: #ffffff;}");
	m_pNameCombo		->setStyleSheet("QComboBox {border: 2px solid #4a95c9; background-color: #4a95c9;    border-radius: 0px;    color: #ffffff;}");
	m_pParityCombo		->setStyleSheet("QComboBox {border: 2px solid #4a95c9; background-color: #4a95c9;    border-radius: 0px;    color: #ffffff;}");
	m_pStopBitsCombo	->setStyleSheet("QComboBox {border: 2px solid #4a95c9; background-color: #4a95c9;    border-radius: 0px;    color: #ffffff;}");

	pOpenButton->setStyleSheet("QPushButton{background-color: #4a95c9; color: #ffffff; border: 1px solid #4a95c9;}");
	pCloseButton->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");
//	pCleanButton->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");
	pSentButton->setStyleSheet("QPushButton{background-color: #b4d3e9; color: #ffffff; border: 1px solid #b4d3e9;}");
	
    if(m_pReadThread->isRunning()) {
        m_pReadThread->stop();
        usleep(100000);
    }

    m_pMySerialPort->close();
}

void SerialPortWidget::cleanReceiveLabel()
{
    m_pReceiveEdit->clear();
/*    m_pSendEdit->setText(""); //发送栏不清空*/
    receivecont=0;
    m_pReciveCountEdit->setText("0");
    sentcont=0;
    m_pSentCountEdit->setText("0");
}

void SerialPortWidget::receiveData(const QString str)
{
    m_pReceiveEdit->appendPlainText(str);
    if(m_pReceiveEdit->document()->blockCount() >= 1000){
        m_pReceiveEdit->document()->clear();
    }
    m_pReciveCountEdit->setText(QString::number(receivecont));
}

